<!--
  传入参数：
  参数名：mapId；                 // 配置初始化显示底图，传入类型：String（数据库中的mining_map对象Id），不传默认第一张地图
  参数名：banMapFlag；            // 配置是否开启禁用切换地图，地图下发地图下拉框是否禁用，不传默认为false，一般同mapId配套使用
-->
<template>
  <el-row style="background:#fff;height:85.5vh;">

    <div v-loading="loading" style="width:100%;height:100%;overflow:hidden;position:relative;" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.8)">
      <BaseMap v-if="selectMap&&selectMap.mapUrl" ref="baseMap" :map-url="selectMap.mapUrl" :layers="selectMap.layers" :projection="selectMap.projection" :bounds="selectMap.bounds" />
      <div id="tips" class="ol-tips">
        <!-- <div id="tips-content" class="width:100%;height:100%;"> -->
        <div v-if="loading === true" class="pswp__preloader__icn">
          <div class="pswp__preloader__cut">
            <div class="pswp__preloader__donut" />
          </div>
        </div>
        <div v-else>
          <div style="width: 60%;height: 100%;float: left;font-size:13px">
            名称:{{ house.name }}<br>
            <span>品牌:{{ house.brand }}<br></span>
            <span>过期时间:{{ house.expireTime }}</span>
          </div>
          <img v-for="item in getPicPath(house)" :key="item" style="float: left" width="64" height="90" :src="baseApi+item">
        </div>
      </div>
      <!--地图工具栏-->
      <div class="map_tool_outbox">
        <el-select v-model="selectMap" :disabled="banMapFlag" value-key="id" placeholder="请选择" style="width: 160px;float:left; margin-left: 1%; margin-top: 10px;" @change="resetMap">
          <el-option v-for="item in mapList" :key="item.id" :label="item.name" :value="item" />
        </el-select>
        <span class="map_tool" @click="zoomOut()">
          <a class="map_tool_inner" title="放大" style="background-image: url('/static/img/map/enlarge.png');" />
        </span>
        <span class="map_tool" @click="zoomIn()">
          <a class="map_tool_inner" title="缩小" style="background-image: url('/static/img/map/narrow.png');" />
        </span>

        <span :class="'map_tool' + (cameraData.markState ? ' map_tool_select':'')" @click="showLayer(cameraData)">
          <a class="map_tool_inner" title="摄像头" style="background-image: url('/static/img/map/camera_blue.png');" />
        </span>
        <span :class="'map_tool' + (cameraData.markState ? ' map_tool_select':'')" @click="showLine()">
          <a class="map_tool_inner" title="自来水" style="background-image: url('/static/img/map/control.png');" />
        </span>
        <span class="map_tool" style="float:right;margin-right:0.6%;" @click="resetMap()">
          <a id="fresh_tool" class="map_tool_inner" title="重置地图" style="background-image: url('/static/img/map/reset.png');" />
        </span>
        <!-- 按钮插槽,按钮样式同上方重置地图按钮 -->
        <slot name="button" />
      </div>
    </div>
  </el-row>
</template>
<script>
import { findAll } from '@/api/mapArea'

import { getWhitePoint } from '@/utils/draw'
import crudBasicMap from '@/api/basicMap'
import BaseMap from './BaseMap'
import 'ol/ol.css'
import Feature from 'ol/Feature'
import Style from 'ol/style/Style'
import Text from 'ol/style/Text'
import Icon from 'ol/style/Icon'
import Fill from 'ol/style/Fill'
import Point from 'ol/geom/Point'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import { mapGetters } from 'vuex'
import { FullScreen, ZoomSlider } from 'ol/control'
import crudHouseEle from '@/api/houseEle'
import Overlay from 'ol/Overlay'
import { getLineFeature } from '@/utils/draw'

// 标注样式图路径配置
export default {
  components: { BaseMap },
  props: {
    mapId: {
      type: String,
      default: () => { return null }
    },
    banMapFlag: {
      type: Boolean,
      default: () => { return false }
    },
    mark: {
      type: Array,
      default: () => { return ['camera'] }
    },
    gisX: {
      type: Number,
      default: () => { return null }
    },
    gisY: {
      type: Number,
      default: () => { return null }
    }
  },
  data() {
    return {
      areaChartLayer: null,
      house: {},
      markerLayer: {},
      loading: false,
      mapList: null,
      selectMap: null,
      cameraData: { type: 'camera', markState: false, layer: null, data: [], onLine: '/static/img/map/camera_blue.png', offLine: '/static/img/map/camera_red.png' }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  mounted() {
    this.getMineMapList()
  },
  methods: {
    getPicPath(row) {
      if (row.picPath) {
        return row.picPath.substr(0, row.picPath.length - 1).split('|')
      }
    },
    showMapMarker() {
      console.log('11')
      const vectorSource = new VectorSource()
      crudHouseEle.getAll().then(res => {
        for (const el of res.content) {
          if (el.gisX && el.gisY) {
            vectorSource.addFeature(getWhitePoint(el, 'house', el.eqName))
          }
        }
      })
      this.markerLayer = new VectorLayer({
        source: vectorSource
      })
      this.$refs.baseMap.map.addLayer(this.markerLayer)
    },
    // 获取地图
    getMineMapList() {
      this.loading = true
      crudBasicMap.getAll().then(res => {
        console.log(res)
        this.mapList = res
        if (res != null && res.length > 0) {
          // 验证是否存在初始地图id，否则默认显示列表中第一个地图
          if (this.mapId) {
            // 匹配id匹配要显示的地图
            for (const item of this.mapList) {
              // 如匹配成功选中地图值为该匹配对象
              if (item.id === this.mapId) {
                this.selectMap = item
                break
              }
            }
          } else {
            this.selectMap = this.mapList[1]
          }
          // 验证是否存在选中地图，存在则初始化显示
          if (this.selectMap && this.selectMap.mapUrl) {
            const that = this
            // 延时加载，确保底图已加载成功
            setTimeout(() => {
              that.initMap()
            }, 50)
          } else {
            this.$message({
              message: '找不到该区域地图，请确认后再重试！',
              type: 'warning'
            })
          }
        } else {
          this.$message({
            message: '暂无配置地图，请先添加配置再重试！',
            type: 'warning'
          })
        }
        this.loading = false
      })
    },
    // 初始化地图
    initMap() {
      this.$refs.baseMap.map.addControl(new FullScreen())
      this.$refs.baseMap.map.addControl(new ZoomSlider())
      this.$refs.baseMap.map.getView().setZoom(13.294567391304351)
      this.showMapMarker()
      var container = document.getElementById('tips')
      // var content = document.getElementById('tips-content')
      var bubble_overlay = new Overlay({
        element: container, // 绑定 Overlay 对象和 DOM 对象的
        positioning: 'center-center'
      })
      // 添加弹框图层
      this.$refs.baseMap.map.addOverlay(bubble_overlay)
      const that = this
      that.$refs.baseMap.map.on('click', function(event) {
        event.preventDefault()
        const feature = that.$refs.baseMap.map.forEachFeatureAtPixel(event.pixel, function(feature, layer) {
          return feature
        })
        console.log(feature)
        if (feature) {
          const type = feature.get('type')
          const data = feature.get('data')
          if (type === 'camera') {
            that.$alert('暂未接入摄像头！', '查看失败', {
              type: 'warning'
            })
          }
          if (type === 'house') {
            if (data.type === '1') {
              that.$router.push({ path: '/myManage/furniture', query: { name: data.name }})
            } else {
              that.$router.push({ path: '/myManage/houseEle', query: { name: data.name }})
            }
          }
        }
      })
      // 监测鼠标悬浮事件
      that.$refs.baseMap.map.on('pointermove', function(event) {
        const feature = that.$refs.baseMap.map.forEachFeatureAtPixel(event.pixel, function(feature, layer) {
          return feature
        })
        if (feature) {
          const type = feature.get('type')
          if (type === 'house') {
            that.house = feature.get('data')
            bubble_overlay.setPosition(event.coordinate)
          }
          that.$refs.baseMap.map.getTargetElement().style.cursor = 'pointer'
        } else {
          if (bubble_overlay.getPosition()) {
            console.log('----')
            bubble_overlay.setPosition(undefined)
          }
          that.$refs.baseMap.map.getTargetElement().style.cursor = 'auto'
          that.$refs.baseMap.map.getTargetElement().style.cursor = 'auto'
        }
      })
    },
    zoomOut() {
      if (this.$refs.baseMap.map) {
        const num = this.$refs.baseMap.map.getView().getZoom() < this.$refs.baseMap.map.getView().getMaxZoom() ? this.$refs.baseMap.map.getView().getZoom() + 1 : this.$refs.baseMap.map.getView().getZoom()
        console.log(num)
        this.$refs.baseMap.map.getView().setZoom(num)
      }
    },
    zoomIn() {
      if (this.$refs.baseMap.map) {
        const num = this.$refs.baseMap.map.getView().getZoom() > this.$refs.baseMap.map.getView().getMinZoom() ? this.$refs.baseMap.map.getView().getZoom() - 1 : this.$refs.baseMap.map.getView().getZoom()
        this.$refs.baseMap.map.getView().setZoom(num)
      }
    },
    showLine() {
      this.$refs.baseMap.map.removeLayer(this.areaChartLayer)
      const vectorSource = new VectorSource()
      // 根据地图id获取区域信息
      console.log(this.selectMap.id)
      findAll(this.selectMap.id).then(res => {
        for (let index = 0; index < res.content.length; index++) {
          const chart = res.content[index]

          if (chart.remark === 'line') {
            // console.log(this.chartObject)
            vectorSource.addFeature(getLineFeature(chart.color, chart.color, chart.name, chart.point, chart.lineWidth))
          } else {
            // vectorSource.addFeature(getAreaFeature(chart.color, chart.color, chart.name, chart.point))
          }
        }
      })
      this.areaChartLayer = new VectorLayer({
        source: vectorSource
      })
      this.$refs.baseMap.map.addLayer(this.areaChartLayer)
    },
    showLayer(deviceData) {
      if (deviceData.layer) {
        this.$refs.baseMap.map.removeLayer(deviceData.layer)
        deviceData.layer = null
      } else {
        const vectorSource = new VectorSource()
        for (const el of deviceData.data) {
          if (el.gisX && el.gisY) {
            const point = new Feature({
              type: deviceData.type,
              data: el,
              geometry: new Point([el.gisX, el.gisY])
            })
            point.setStyle(new Style({
              image: new Icon({
                src: deviceData.onLine,
                anchor: [0.5, 0.9], // 图标定位，0.5为中间，[左右，上下]
                scale: 0.2 // 图标大小
              }),
              text: new Text({
                font: 'bold 12px sans-serif',
                text: el.name, // 显示名称
                offsetY: 12,
                fill: new Fill({ color: '#333' }),
                backgroundFill: new Fill({ color: 'rgba(255,255,255,0.7)' })
              })
            }))
            vectorSource.addFeature(point)
          }
        }

        deviceData.layer = new VectorLayer({
          source: vectorSource
        })
        this.$refs.baseMap.map.addLayer(deviceData.layer)
      }
      deviceData.markState = !deviceData.markState
    },
    resetMap() {
      this.$refs.baseMap.resetBaseMap()
      this.$refs.baseMap.map.updateSize()
    }
  }
}
</script>
<style lang="scss" scoped>
#map { height: 100%; width: 100%; }
/*隐藏ol的一些自带元素*/
.ol-attribution,.ol-zoom { display: none; }
/*底部菜单栏*/
.map_tool_outbox{ width: 100%; background-image: url("/static/img/map/map_tool_bg.png"); height:50px; cursor: auto; background-repeat: repeat-x; position: absolute; bottom: 0; border-radius: 0 0 5px 5px;}
.map_tool{ display: block; width: 40px; height: 100%; margin-left: 8px; cursor: pointer; float: left;}
.map_tool:hover{ background-image:url("/static/img/map/map_tool_re.png"); background-repeat: repeat-x;}
.map_tool_select{ background-image:url("/static/img/map/map_tool_re.png"); background-repeat: repeat-x;}
.map_tool_inner{ display: block; width: 100%; height: 100%; background-image: url('/static/img/map/reset.png'); background-position:center center; background-repeat:no-repeat; background-size: 60% auto;}
/* 菜单弹框 */
.ol_menu{ width: 100PX; background: rgb(255, 255, 255); box-shadow: rgba(0, 0, 0, 0.075) 0 1px 1px inset, rgba(102, 175, 233, 0.6) 0 0 8px; position: fixed; text-align: center; padding: 5px; box-sizing: content-box; }
.ol_menu_ul{   padding: unset; margin: unset; display: inline-block; width: 100%; }
.ol_menu_ul>li{ font-size:14px; line-height:20px; cursor: pointer; list-style: none; border-bottom: 1px solid #efefef; padding: 7px 10px; }
.ol_menu_ul>li:last-child { border: unset }
.ol_menu_ul>li:hover{ background: #ccc; color: #fff; }
 .ol-tips {
    width: 200PX;
    position: absolute;
    background-color: #0080ff;
    opacity: 0.9;
    padding: 10px 10px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px; left: -50px;
    color: #ffffff;
  }

  .pswp__preloader__icn {
    opacity:0.75;
    width: 24px;
    height: 24px;
    -webkit-animation: clockwise 500ms linear infinite;
    animation: clockwise 500ms linear infinite;
  }

  /* The idea of animating inner circle is based on Polymer loading indicator by Keanu Lee https://blog.keanulee.com/2014/10/20/the-tale-of-three-spinners.html */
  .pswp__preloader__cut {
    position: relative;
    width: 12px;
    height: 24px;
    overflow: hidden;
    position: absolute;
    top: 0;
    left: 0;
  }
</style>
